/**
 * 
 */
package no.ntnu.item.ttm4115.termproject.callhelprole_playeragent.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.AbstractAction;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;

import no.ntnu.item.ttm4115.termproject.extrasagent.Location;
import no.ntnu.item.ttm4115.termproject.extrasagent.Player;
import no.ntnu.item.ttm4115.termproject.extrasagent.Preferences;
import no.ntnu.item.ttm4115.termproject.playeragent.PlayerAgentSM;
import no.ntnu.item.ttm4115.termproject.playeragent.gui.MeetingPlaceGUI;
import no.ntnu.item.ttm4115.termproject.socialmatchingrole_playeragent.SocialMatchingRole_PlayerAgentSM;
import no.ntnu.item.ttm4115.termproject.socialmatchingrole_playeragent.gui.ClueTab;
import no.tellu.common.actorframe.ActorSM;

import org.jdesktop.layout.GroupLayout;
import org.jdesktop.layout.LayoutStyle;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
/**
 * @author item
 *
 */
public class Call4Help extends javax.swing.JPanel{

	{
		//Set Look & Feel
		try {
			javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	private AbstractAction abstractActionTest;
	private JPanel jPanelPreferences;
	private JLabel jLabelPlayingGroupsUsers;
	private JLabel jLabelStatus;
	private JList jListAvailableUsersForHelp;
	private JComboBox jComboBoxStatus;
	private JTabbedPane jTabbedPaneCall4Help;
	private JLabel jLabelInterests;
	private JTextArea jTextAreaDob;
	private AbstractAction abstractActionHelp;
	private AbstractAction abstractActionStop;
	private JButton jButtonHelp;
	private JButton jButtonStop;
	private JTextArea jTextAreaInterests;
	private JLabel jLabelDob;

	private String userAddress = "Surya";
	private JLabel jLabelUserName;

	private DefaultListModel jListMatchedUsersModel= new  DefaultListModel();
	private DefaultListModel jListEmergingGroupsModel= new  DefaultListModel();
	
    private ActorSM asm;
    public ActorSM getAsm() {
		return asm;
	}

    
    private MeetingPlaceGUI meetingPlace;
	private Player player;
    private Preferences preferences;
	private Location locations;
    
	private JFrame mainFrame;

	/**
	* Auto-generated main method to display this 
	* JPanel inside a new JFrame.
	*/
	public static void main(String[] args) {

    	JFrame frame = new JFrame();
		frame.getContentPane().add(new Call4Help());
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
		frame.setLocationRelativeTo(null);
	}
	
	public Call4Help() {
		super();
		initGUI();
		ClueTab clueTab = new ClueTab();
		clueTab.setRootPanel(this);
		getJTabbedPaneCall4Help().addTab("Location Update", clueTab);
		jTabbedPaneCall4Help.addTab("Call for Help", getJPanelPreferences());
	}
	
	public Call4Help(MeetingPlaceGUI meetingPlace, Player player, ActorSM asm){
		super();
		this.meetingPlace = meetingPlace;
		this.player = player;
		this.asm = asm;
		initGUI();
		ClueTab clueTab = new ClueTab();
		clueTab.setRootPanel(this);
		getJTabbedPaneCall4Help().addTab("Location Update", clueTab);
		clueTab.setPreferredSize(new java.awt.Dimension(680, 327));
		jTabbedPaneCall4Help.addTab("Call for Help", getJPanelPreferences());
	}
	
	private void initGUI() {
		try {
			GroupLayout thisLayout = new GroupLayout((JComponent)this);
			this.setLayout(thisLayout);
			thisLayout.setVerticalGroup(thisLayout.createSequentialGroup()
				.addContainerGap(16, 16)
				.add(thisLayout.createParallelGroup()
				    .add(GroupLayout.LEADING, thisLayout.createSequentialGroup()
				        .add(getJLabelPlayingGroupsUsers(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				        .addPreferredGap(LayoutStyle.RELATED)
				        .add(getJListAvailableUsersForHelp(), GroupLayout.PREFERRED_SIZE, 234, GroupLayout.PREFERRED_SIZE)
				        .addPreferredGap(LayoutStyle.UNRELATED)
				        .add(getJLabelstatus(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				        .addPreferredGap(LayoutStyle.RELATED)
				        .add(getJComboBoxStatus(), GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)
				        .add(50))
				    .add(GroupLayout.LEADING, getJTabbedPaneCall4Help(), 0, 355, Short.MAX_VALUE))
				.addContainerGap());
			thisLayout.setHorizontalGroup(thisLayout.createSequentialGroup()
				.addContainerGap()
				.add(thisLayout.createParallelGroup()
				    .add(GroupLayout.LEADING, getJLabelPlayingGroupsUsers(), GroupLayout.PREFERRED_SIZE, 149, GroupLayout.PREFERRED_SIZE)
				    .add(GroupLayout.LEADING, getJListAvailableUsersForHelp(), GroupLayout.PREFERRED_SIZE, 146, GroupLayout.PREFERRED_SIZE)
				    .add(GroupLayout.LEADING, thisLayout.createSequentialGroup()
				        .add(getJLabelstatus(), GroupLayout.PREFERRED_SIZE, 115, GroupLayout.PREFERRED_SIZE)
				        .add(34))
				    .add(GroupLayout.LEADING, thisLayout.createSequentialGroup()
				        .add(getJComboBoxStatus(), 0, 143, Short.MAX_VALUE)
				        .add(6)))
				.add(getJTabbedPaneCall4Help(), 0, 700, Short.MAX_VALUE));
			this.setPreferredSize(new java.awt.Dimension(859, 382));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public JTabbedPane getJTabbedPaneCall4Help() {
		if(jTabbedPaneCall4Help == null) {
			jTabbedPaneCall4Help = new JTabbedPane();
		}
		return jTabbedPaneCall4Help;
	}

	public JList getJListAvailableUsersForHelp() {
		if(jListAvailableUsersForHelp == null) {	
			jListAvailableUsersForHelp = new JList();
			jListAvailableUsersForHelp.setModel(getJListMatchedUsersModel());
			// test user
			//dummyUsersList();
			jListAvailableUsersForHelp.addMouseListener(
					new MouseAdapter() {
						public void mouseReleased( MouseEvent e ) {
							if (e.isPopupTrigger()) {
								popupToUserList().show( (JComponent)e.getSource(), e.getX(), e.getY() );
							}
						}
					}
			);
		}
		return jListAvailableUsersForHelp;
	}
	public JComboBox getJComboBoxStatus() {
		String[] items = new String[]{"available", "busy","absemt"};
		if(jComboBoxStatus == null) {	
			jComboBoxStatus = new JComboBox(items);
			
			jComboBoxStatus.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					
					jComboBoxStatus_statusChanged(e);
				}
				
			});
			
		}
		return jComboBoxStatus;
	}
	
	//method to fire status change event
	public void jComboBoxStatus_statusChanged(ActionEvent e){
		// get the selected object
		Object o = jComboBoxStatus.getSelectedItem();
		
		System.out.println("status changed in call 4 help service tab");
		
		// send this information to the server
		// asm.sendMessage(your signal, to address);
	}
	
	public JLabel getJLabelPlayingGroupsUsers() {
		if(jLabelPlayingGroupsUsers == null) {
			jLabelPlayingGroupsUsers = new JLabel();
			jLabelPlayingGroupsUsers.setText("Available users for Help");
		}
		return jLabelPlayingGroupsUsers;
	}
	public JLabel getJLabelstatus(){
		if(jLabelStatus == null) {
			jLabelStatus = new JLabel();
		jLabelStatus.setText("My status");
	}
	return jLabelStatus;
	}

    public DefaultListModel getJListMatchedUsersModel(){ 	
    	return jListMatchedUsersModel;
    }
    
    // here you need to update the list of available users for help
    // call this method from CallhelpRole_PlayerAgentActions class when user available for help is received
    public void updateAvailableUsersList(Player p){
    	
    	getJListMatchedUsersModel().addElement(p);
    	
 /*   	//update online player map
    	((PlayerAgentSM)((SocialMatchingRole_PlayerAgentSM)asm).mainFrame.getAsm()).onlinePlayersMap.put(p.getUserName(),p);
    	
    	//redraw matched user 
    	getJListMatchedUsersModel().clear();
    	ArrayList<Integer> index = new ArrayList<Integer>();
    	for(int i=0; i< p.getMatchList().size(); i++) getJListMatchedUsersModel().addElement(p.getMatchList().get(i).getUserName()+"("+p.getMatchList().get(i).getLocation()+") "+p.getMatchList().get(i).getStatus());			 	
  */  
    }
    
   /* private void dummyUsersList(){
    	
    	getJListMatchedUsersModel().addElement("Test User1");
    	getJListMatchedUsersModel().addElement("Test User2");
    	getJListMatchedUsersModel().addElement("Test User3");
    	   	
   		Iterator<Map.Entry> playerit = ((PlayerAgentSM)((SocialMatchingRole_PlayerAgentSM)asm).mainFrame.getAsm()).onlinePlayersMap.entrySet().iterator();
    		while(playerit.hasNext()){
    			Map.Entry me = (Map.Entry)playerit.next();
    			Player player = (Player)me.getValue();
    			if (!this.player.getUserName().equals(player.getUserName())){
    				getJListMatchedUsersModel().addElement(player.getUserName()+"("+player.getLocation()+") "+player.getStatus());			
    			}
    		}
        	
    }*/
    
    private JPopupMenu popupToUserList(){

		JPopupMenu popup;
		JMenuItem mi;
		
		popup = new JPopupMenu();	
		
		mi = new JMenuItem("Start Chat");
		mi.addActionListener(new PopupListener());
		mi.setActionCommand("startchat");
		popup.add(mi);
			
		popup.setOpaque(true);
		popup.setLightWeightPopupEnabled(true);
		return popup;   	
	}
    
    public JPanel getJPanelPreferences() {
    	if(jPanelPreferences == null) {
    		jPanelPreferences = new JPanel();
    		GroupLayout jPanelPreferencesLayout = new GroupLayout((JComponent)jPanelPreferences);
    		jPanelPreferences.setLayout(jPanelPreferencesLayout);
    		jPanelPreferencesLayout.setHorizontalGroup(jPanelPreferencesLayout.createSequentialGroup()
    			.addContainerGap()
    			.add(jPanelPreferencesLayout.createParallelGroup()
    			    .add(GroupLayout.LEADING, jPanelPreferencesLayout.createSequentialGroup()
    			        .add(getJLabelInterests(), GroupLayout.PREFERRED_SIZE, 140, GroupLayout.PREFERRED_SIZE)
    			        .add(33)
    			        .add(getJTextAreaInterests(), GroupLayout.PREFERRED_SIZE, 346, GroupLayout.PREFERRED_SIZE)
    			        .add(0, 0, Short.MAX_VALUE))
    			    .add(GroupLayout.LEADING, jPanelPreferencesLayout.createSequentialGroup()
    			        .add(getJLabelUserName(), GroupLayout.PREFERRED_SIZE, 514, GroupLayout.PREFERRED_SIZE)
    			        .addPreferredGap(LayoutStyle.RELATED, 0, Short.MAX_VALUE))
    			    .add(GroupLayout.LEADING, jPanelPreferencesLayout.createSequentialGroup()
    			        .add(131)
    			        .add(getJButtonStop(), GroupLayout.PREFERRED_SIZE, 145, GroupLayout.PREFERRED_SIZE)
    			        .add(69)
    			        .add(getJButtonHelp(), GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE)
    			        .add(0, 0, Short.MAX_VALUE)))
    			.addContainerGap(201, 201));
    		jPanelPreferencesLayout.setVerticalGroup(jPanelPreferencesLayout.createSequentialGroup()
    			.addContainerGap()
    			.add(getJLabelUserName(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
    			.add(16)
    			.add(jPanelPreferencesLayout.createParallelGroup()
    			    .add(GroupLayout.LEADING, getJTextAreaInterests(), GroupLayout.PREFERRED_SIZE, 107, GroupLayout.PREFERRED_SIZE)
    			    .add(GroupLayout.LEADING, jPanelPreferencesLayout.createSequentialGroup()
    			        .add(34)
    			        .add(getJLabelInterests(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
    			        .add(59)))
    			.add(19)
    			.add(jPanelPreferencesLayout.createParallelGroup(GroupLayout.BASELINE)
    			    .add(GroupLayout.BASELINE, getJButtonStop(), GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
    			    .add(GroupLayout.BASELINE, getJButtonHelp(), GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE))
    			.addContainerGap(138, 138));
    	}
    	return jPanelPreferences;
    }

    private JPopupMenu popupToGroupsList(){

		JPopupMenu popup;
		JMenuItem mi;
		
		popup = new JPopupMenu();	
		
		mi = new JMenuItem("Start Group Chat");
		mi.addActionListener(new PopupListener());
		mi.setActionCommand("startgroupchat");
		popup.add(mi);
			
		popup.setOpaque(true);
		popup.setLightWeightPopupEnabled(true);
		return popup;   	
	}
    
    public DefaultListModel getJListEmergingGroupsModel(){ 	
    	return jListEmergingGroupsModel;
    }
    
    private void dummyGroupsList(){
    	
    	getJListEmergingGroupsModel().addElement("Test Group1");
    	getJListEmergingGroupsModel().addElement("Test Group2");
    	getJListEmergingGroupsModel().addElement("Test Group3");
    
    
    }
    
    public void setGroupList(String group){
    	
    	getJListEmergingGroupsModel().clear();
    	getJListEmergingGroupsModel().addElement(group);
    }
    
    
    public JLabel getJLabelUserName() {
    	if(jLabelUserName == null) {
    		jLabelUserName = new JLabel();
    		jLabelUserName.setText("Click \"ask for help\" button when you need help.");
    	}
    	return jLabelUserName;
    }


    
    public JLabel getJLabelInterests() {
    	if(jLabelInterests == null) {
    		jLabelInterests = new JLabel();
    		jLabelInterests.setText("short help description:");
    	}
    	return jLabelInterests;
    }

    public JButton getJButtonStop() {
    	if(jButtonStop == null) {
    		jButtonStop = new JButton();
    		jButtonStop.setText("Stop");
    		jButtonStop.setAction(getAbstractStop());
    	}
    	return jButtonStop;
    }
    
    public JTextArea getJTextAreaInterests() {
    	if(jTextAreaInterests == null) {
    		jTextAreaInterests = new JTextArea();
    		jTextAreaInterests.setText("add a few help description.");
    	}
    	return jTextAreaInterests;
    }
    
    public JButton getJButtonHelp() {
    	if(jButtonHelp == null) {
    		jButtonHelp = new JButton();
    		jButtonHelp.setText("ask for help");
    		jButtonHelp.setAction(getAbstractHelp());
    	}
    	return jButtonHelp;
    }
    private AbstractAction getAbstractHelp() {
    	jButtonStop.setEnabled(false);
    	if(abstractActionHelp == null) {
    		abstractActionHelp = new AbstractAction("ask for help", null) {
    			public void actionPerformed(ActionEvent evt) {
    				
    				helpUpdated(getJTextAreaInterests().getText());
    			}
    		};
    	}

    	return abstractActionHelp;
    }
    private AbstractAction getAbstractStop() {
    	if(abstractActionStop == null) {
    		abstractActionStop = new AbstractAction("Stop", null) {
    			public void actionPerformed(ActionEvent evt) {
    				
    				StopUpdated(getJTextAreaInterests().getText());
    			}
    		};
    	}
    	return abstractActionStop;
    }
    
    
    public void updateEmergingGroups(){
    	
    }
    
    public void updateMatchedusers(Player p){
    	
    	//update online player map
    	((PlayerAgentSM)((SocialMatchingRole_PlayerAgentSM)asm).mainFrame.getAsm()).onlinePlayersMap.put(p.getUserName(),p);
    	
    	//redraw matched user 
    	getJListMatchedUsersModel().clear();
    	for(int i=0; i< p.getMatchList().size(); i++) getJListMatchedUsersModel().addElement(p.getMatchList().get(i).getUserName()+"("+p.getMatchList().get(i).getLocation()+") "+p.getMatchList().get(i).getStatus());			
    
    	
    }
    
    class PopupListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			if(e.getActionCommand().endsWith("startchat")){
				// write event handlers code
							
				String temp = jListAvailableUsersForHelp.getSelectedValue().toString(); 			
				meetingPlace.showIMWindow(temp);
				
			}
			if(e.getActionCommand().endsWith("startgroupchat")){
				// write event handlers code
				System.out.println("start group chat here...");
				//String temp = jListEmergingGroups.getSelectedValue().toString();
				meetingPlace.showGrChtWindow();
				
			}
		}
	}

	public String getUserAddress() {
		return userAddress;
	}

	public void setUserAddress(String userAddress) {
		this.userAddress = userAddress;
	}

	public Player getPlayer() {
		return player;
	}

	public void setPlayer(Player player) {
		this.player = player;
	}

	public Preferences getPreferences() {
		return preferences;
	}

	public void setPreferences(Preferences preferences) {
		this.preferences = preferences;
	}

	public Location getLocations() {
		return locations;
	}

	public void setLocations(Location locations) {
		this.locations = locations;
	}
	
	// Location Update Event received
	public void locationUpdated(Location locations){
		System.out.println("location updated..:"+locations);
		asm.sendMessage(new no.ntnu.item.ttm4115.termproject.Location(locations.getX(),locations.getY()),asm.getMyActorAddress());
	}

	//preferences update events received
	public void StopUpdated(String helpDesc){
		System.out.println("stop updated..:"+helpDesc);		
		//		asm.sendMessage(, asm.getMyActorAddress());
		
		// disable this button and enable ask help button
		jButtonHelp.setEnabled(true);
		jButtonStop.setEnabled(false);
	}
	public void helpUpdated(String helpDesc){
		System.out.println("help updated..:"+helpDesc);	
		
		//			asm.sendMessage(, asm.getMyActorAddress());
		
	
		// disable this button and enable stop button
		jButtonHelp.setEnabled(false);
		jButtonStop.setEnabled(true);
	}
		
}